package com.zheng.shop.rpc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.shop.common.exception.ShopException;
import com.zheng.shop.dao.mapper.ShopAttributeKeyMapper;
import com.zheng.shop.dao.model.ShopAttributeKey;
import com.zheng.shop.dao.model.ShopAttributeValue;
import com.zheng.shop.dao.model.ShopCategory;
import com.zheng.shop.dao.model.ShopProduct;
import com.zheng.shop.rpc.api.ShopAttributeKeyService;
import com.zheng.shop.rpc.api.ShopAttributeValueService;
import com.zheng.shop.rpc.api.ShopCategoryService;
import com.zheng.shop.rpc.api.ShopProductService;
import org.mybatis.generator.codegen.ibatis2.sqlmap.elements.UpdateByExampleSelectiveElementGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author likun
 * @since 2017-12-29
 */
@Service
@Transactional(rollbackFor = ShopException.class)
@BaseService
public class ShopAttributeKeyServiceImpl extends BaseServiceImpl<ShopAttributeKeyMapper, ShopAttributeKey> implements ShopAttributeKeyService {
    private static Logger _log = LoggerFactory.getLogger(ShopAttributeKeyServiceImpl.class);

    @Autowired
    private ShopProductService productService;
    @Autowired
    private ShopAttributeKeyMapper keyMapper;
    @Autowired
    private ShopAttributeValueService valueService;
    @Autowired
    private ShopCategoryService categoryService;

    @Override
    public boolean createProductAttribute(Integer productCategoryId, String keyName, List<String> values) throws ShopException {
        ShopAttributeKey key = new ShopAttributeKey();
        key.setKeyName(keyName);
        key.setCategoryId(productCategoryId);
        key.setHasImage(false);
        if (keyMapper.insert(key) < 1) {
            throw new ShopException("添加属性" + keyName + "失败！");
        }
        for (String value : values) {
            ShopAttributeValue attributeValue = new ShopAttributeValue();
            attributeValue.setKeyId(key.getId());
            attributeValue.setValueName(value);
            if (!valueService.insert(attributeValue)) {
                throw new ShopException("添加属性值" + value + "失败！");
            }
        }
        return true;
    }

    @Override
    public boolean updateProductAttribute(Integer keyId, String keyName, List<String> values) throws ShopException {
        ShopAttributeKey attributeKey = selectById(keyId);
        attributeKey.setKeyName(keyName);

        EntityWrapper<ShopAttributeValue> attributeValueEntityWrapper = new EntityWrapper<>();
        attributeValueEntityWrapper.where("key_id=" + keyId);
        //fixme 失败就失败吧？
        valueService.delete(attributeValueEntityWrapper);
        for (String value : values) {
            ShopAttributeValue attributeValue = new ShopAttributeValue();
            attributeValue.setValueName(value);
            attributeValue.setKeyId(keyId);
            if (!valueService.insert(attributeValue)) {
                throw new ShopException("添加属性值" + value + "失败！");
            }
        }
        if (!updateById(attributeKey)) {
            throw new ShopException("修改属性失败！");
        }
        return true;
    }

    @Override
    public boolean deleteProductAttribute(Integer keyId) throws ShopException {
        EntityWrapper<ShopAttributeValue> attributeValueEntityWrapper = new EntityWrapper<>();
        attributeValueEntityWrapper.where("key_id=" + keyId);
        if (valueService.delete(attributeValueEntityWrapper)) {
            if (!deleteById(keyId)) {
                throw new ShopException("删除属性失败！");
            }
        } else {
            throw new ShopException("删除属性失败！");
        }
        return true;
    }

    @Override
    public boolean deleteProductAttribute(List<Integer> keyIdList) throws ShopException {
        for (Integer keyId : keyIdList) {
            deleteProductAttribute(keyId);
        }
        return true;
    }

    @Override
    public boolean copyProductAttribute(List<Integer> keyIdList, Integer productCategoryId) throws ShopException {
        for (Integer keyId : keyIdList) {
            ShopAttributeKey attributeKey = selectById(keyId);
            attributeKey.setId(null);
            attributeKey.setCategoryId(productCategoryId);
            if (!insert(attributeKey)) {
                throw new ShopException("复制属性" + attributeKey.getKeyName() + "失败！");
            }
            EntityWrapper<ShopAttributeValue> attributeValueEntityWrapper = new EntityWrapper<>();
            attributeValueEntityWrapper.where("key_id=" + keyId);
            List<ShopAttributeValue> attributeValues = valueService.selectList(attributeValueEntityWrapper);
            for (ShopAttributeValue attributeValue : attributeValues) {
                attributeValue.setKeyId(attributeKey.getId());
                attributeValue.setId(null);
                if (!valueService.insert(attributeValue)) {
                    throw new ShopException("复制属性值" + attributeValue.getValueName() + "失败！");
                }
            }
        }
        return true;
    }

    public JSONArray getKeyValueJson(Integer productCategoryId) {
        JSONArray jsonArray = new JSONArray();
        List<ShopAttributeKey> keyList = getKeyListByProductCategoryId(productCategoryId);
        for (ShopAttributeKey key : keyList) {
            List<ShopAttributeValue> valueList = valueService.getValueListByKeyId(key.getId());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", key);
            jsonObject.put("valueList", valueList);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    private List<ShopAttributeKey> getKeyListByProductCategoryId(Integer productCategoryId) {
        EntityWrapper<ShopAttributeKey> attributeKeyEntityWrapper = new EntityWrapper<>();
        attributeKeyEntityWrapper.where("category_id=" + productCategoryId);
        return selectList(attributeKeyEntityWrapper);
    }

    @Override
    public boolean selectImage(Integer id, boolean hasImage) throws ShopException {
        ShopAttributeKey shopAttributeKey = selectById(id);
        //如果该分类下有商品，不允许修改
        ShopCategory category = categoryService.selectById(shopAttributeKey.getCategoryId());
        EntityWrapper<ShopProduct> productEntityWrapper = new EntityWrapper<>();
        productEntityWrapper.where("product_category_id=" + category.getId());
        List<ShopProduct> productList = productService.selectList(productEntityWrapper);
        if (productList.size() > 0) {
            throw new ShopException("该分类下有已经添加的商品，不能进行操作！");
        }
        //设置为有才需要这些操作
        if (hasImage) {
            EntityWrapper<ShopAttributeKey> attributeKeyEntityWrapper = new EntityWrapper<>();
            attributeKeyEntityWrapper.where("has_image=" + true);
            List<ShopAttributeKey> shopAttributeKeys = selectList(attributeKeyEntityWrapper);
            for (ShopAttributeKey attributeKey : shopAttributeKeys) {
                attributeKey.setHasImage(false);
            }
            if (shopAttributeKeys.size() > 0) {
                if (!updateBatchById(shopAttributeKeys)) {
                    throw new ShopException("修改有图失败！");
                }
            }
        }
        shopAttributeKey.setHasImage(hasImage);
        updateById(shopAttributeKey);
        return true;
    }
}
